package com.wish.finance.alipay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class AlibabapayGateWayUtils {


    /**
     *
     * @param orderID 订单号
     * @param total_amount 支付金额
     * @param subject  商品名称
     * @param body 商品描述
     * @return
     */
    public static String createOrder(String orderID,String total_amount,String subject,String body) throws AlipayApiException {
        Map<String,String> map = new HashMap<>();
        map.put("out_trade_no",orderID);
        map.put("trade_no",orderID);
        map.put("total_amount",total_amount);
        map.put("subject",subject);
        map.put("body",body);

        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "1c";
        map.put("timeout_express",timeout_express);
        //统一收单下单并支付页面接口
        map.put("product_code","FAST_INSTANT_TRADE_PAY");

        AlipayClient alipayClient = getAlipayClient();

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizContent(JSON.toJSONString(map));

        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return  result;
    }

    private static AlipayClient getAlipayClient() {
        return new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
    }


    /**
     * 查询订单
     * @param map
     * @return @RequestMapping(value = "goPay", produces = "text/html; charset=UTF-8")  AlibabapayGateWayUtils.createOrder
     * @throws AlipayApiException
     */
    @PostMapping("queryOrder")
    public static  AlipayTradeQueryResponse queryOrder(Map<String, String> map) throws AlipayApiException {
        System.err.println("回调了");
        AlipayClient alipayClient = getAlipayClient();
        //构造API请求
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent(JSON.toJSONString(map));//订单允许的最晚付款时间
        //发送请求
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println("请求支付宝查询接口返回的结果为:"+response.getBody());
        return response;
    }
}
